package com.programming.forum.controller;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22479
 * Date: 2023-11-06
 * Time: 10:22
 */

import com.programming.forum.common.AppResult;
import com.programming.forum.common.ResultCode;
import com.programming.forum.config.AppConfig;
import com.programming.forum.model.User;
import com.programming.forum.services.impl.MessageServiceImpl;
import com.programming.forum.services.impl.UserServiceImpl;
import com.programming.forum.utils.MD5Util;
import com.programming.forum.utils.StringUtil;
import com.programming.forum.utils.UUIDUtil;
import com.sun.istack.internal.NotNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 用户业务逻辑
 */
//日志
@Slf4j
@RestController
@RequestMapping("/user")
//对Controller进行Api注解
@Api(tags="用户业务逻辑接口")
public class UserController {

    @Resource
    private UserServiceImpl userService;
    @Resource
    private MessageServiceImpl messageService;

    /**
     * 用户注册api
     * 功能: 接受用户请求 参数校验 初始化新用户数据 响应
     * @param username 用户名
     * @param nickname  昵称
     * @param password  密码
     * @param passwordRepeat    确认密码
     * @return
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public AppResult register(@ApiParam("用户名") @RequestParam("username")  @NotNull String username,
                              @ApiParam("昵称") @RequestParam("nickname")  @NotNull String nickname,
                              @ApiParam("密码") @RequestParam("password")  @NotNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat")  @NotNull String passwordRepeat) {
        //传统参数校验
//        //参数校验 不通过给前端返回错误响应
//        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(nickname) || StringUtil.isEmpty(password) || StringUtil.isEmpty(passwordRepeat) ) {
//            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//        }

        //密码与确认密码校验
        if(!password.equals(passwordRepeat)) {
            log.info(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        //准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //密码加密
        //1.生成盐
        String salt = UUIDUtil.UUID_32();
        //生成密码的密文
        String ciphertext = MD5Util.md5Salt(password,salt);

        //设置密码和盐
        user.setPassword(ciphertext);
        user.setSalt(salt);
        //调用service层方法
        userService.createNormalUser(user);
        //查询新用户的用户信息
        User newUser = userService.selectByUserName(username);
        messageService.welComNewUser(newUser.getId());
        log.info(user.toString());
        return AppResult.success(ResultCode.SUCCESS);
    }


    /**
     * 用户登录api
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public AppResult login(@ApiParam("用户名") @RequestParam("username") @NotNull String username,
                           @ApiParam("密码") @RequestParam("password") @NotNull String password,
                           HttpServletRequest request) {
        //调用service中的登录方法
        User user = userService.login(username, password);
        if(user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }

        //登录成功将返回的user加入到session中

        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);

        //返回结果
        return AppResult.success();
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult getUserInfo(HttpServletRequest request,
                                 @ApiParam("用户Id") @RequestParam(value = "id" , required = false) Long id) {
        //如果id为空, 从session中获取当前登录信息
        User user = null;
        //根据Id是否为空选择获取用户信息的方式
        if( id == null) {
            HttpSession session = request.getSession(false);
            if(session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
                //用户没有登录,返回错误信息 FAILED_FORBIDDEN        (1003, "禁止访问"),
                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
            }
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        } else {
            //id不为空, 从数据库查询用户信息
            user = userService.selectById(id);
        }
        //判断用户对象是否为空
        if(user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);

    }

    @ApiOperation(("退出登录"))
    @PostMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        //获取session对象
        HttpSession session = request.getSession(false);
        if(session == null) {
            //用户没有登录,返回错误信息 FAILED_FORBIDDEN        (1003, "禁止访问"),
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        log.info("退出成功");
        //直接销毁session 并且解绑数据
        session.invalidate();
        return AppResult.success("退出成功");
    }

    /**
     * 修改个人信息
     * @param nickname 昵称
     * @param email 邮箱
     * @param phoneNum 电话号
     * @param remark 个人简介
     * @return AppResult
     */
    @ApiOperation("修改用户信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("昵称") @RequestParam(value ="nickname" ,required = false) String nickname,
                                @ApiParam("邮箱") @RequestParam(value ="email" ,required = false) String email,
                                @ApiParam("电话号码") @RequestParam(value ="phoneNum" ,required = false) String phoneNum,
                                @ApiParam("个人简介") @RequestParam(value ="remark" ,required = false) String remark) {

        // 1. 接收参数
        // 2. 对参数做非空校验（全部都为空，则返回错误描述）
        if ( StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark) ) {
            // 返回错误信息
            return AppResult.failed("请做出修改");
        }

        //获取对象信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //构建更新user
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setNickname(nickname); // 昵称
        updateUser.setEmail(email); // 邮箱
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setRemark(remark); // 个人简介

        //调用dao层
        userService.modifyInfo(updateUser);
        //查询最新的用户信息
        user = userService.selectById(user.getId());
        //更新到session中
        session.setAttribute(AppConfig.USER_SESSION,user);


        return AppResult.success(user);
    }


    @ApiOperation("修改密码")
    @PostMapping("/modifyPassword")
    public AppResult modifyPassWord(HttpServletRequest request,
                                    @ApiParam("旧密码") @RequestParam("oldPassword") @NotNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NotNull String newPassword,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat") @NotNull String passwordRepeat) {
        //校验新密码与确认密码是否相同
        if(!newPassword.equals(passwordRepeat)) {
            //FAILED_TWO_PWD_NOT_SAME (1106,"两次输入的密码不一致"),
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        //获取当前登录用户信息
        //获取对象信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //调用service
        userService.modifyPassWord(user.getId(), newPassword,oldPassword);
        //销毁session
        if(session != null) {
            session.invalidate();
        }
        //返回结果
        return AppResult.success();
    }



}
